import pymysql
from wordcloud import WordCloud
import pygal
import jieba
# 1. 从数据库把所有用户评论取出
# 2. 所有用户评论拼成一个长字符串
# 3. 长字符串用jieba分词
# 4. 拼成词云使用的结构
# 5. pygal 根据用户color，size 统计比例，查询pygal 饼状图文档。


def get_comments():
    # 连接数据库
    # 读表
    # select content from
    db = pymysql.connect(host='127.0.0.1',
                         port=3306,
                         user='root',
                         password='123456',
                         db='taobao',
                         charset='utf8mb4')
    with db.cursor() as cursor:
        sql = 'select ratecontent,content from taobao.table_name'
        cursor.execute(sql)
        s_c = cursor.fetchall()
        for con in s_c:
            # print(con)
            don = ''.join(con)
            # print(don)
            jieba_content(don)
        db.commit()
        # 关闭数据库连接
        db.close()
        # print(res)


def jieba_content(don):
    results = jieba.cut(don, cut_all=False)
    # print(results)
    word_list = []
    for i in results:  # 生成器只能取一次
        print(i)
        word_list.append(i)
    # print(word_list)
    word_taobao_list = ' '.join(word_list)
    # print(word_taobao_list)
    ciyun(word_taobao_list)

def ciyun(word_taobao_list):
    string = word_taobao_list
    font = 'C:\Windows\Fonts\msyhbd.ttf'
    wc = WordCloud(font_path=font,
                   background_color='white',
                   width=1000,
                   height=800,
                   ).generate(string)
    wc.to_file('3词云-淘宝.png')  # 保存图片


if __name__ == '__main__':
    get_comments()